#include "drink.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h> // Needed for snprintf

// 加载所有饮品信息到链表，返回饮品数量
// filename is expected to be the base filename (e.g., "drinks.dat")
int load_drinks(const char* filename, DrinkNode** head) {
    char full_path[1024];
    // Construct the full path using the macro defined in CMakeLists.txt
    snprintf(full_path, sizeof(full_path), "%s/%s", SOURCE_DATA_PATH, filename);

    FILE* fp = fopen(full_path, "rb");
    if (!fp) {
        // Optional: Print an error message if file couldn't be opened
        // perror(full_path);
        *head = NULL;
        return 0;
    }
    Drink temp;
    int count = 0;
    *head = NULL;
    DrinkNode* tail = NULL;
    while (fread(&temp, sizeof(Drink), 1, fp) == 1) {
        DrinkNode* node = (DrinkNode*)malloc(sizeof(DrinkNode));
        if (!node) break;
        node->data = temp;
        node->next = NULL;
        if (*head == NULL) {
            *head = node;
        } else {
            tail->next = node;
        }
        tail = node;
        count++;
    }
    fclose(fp);
    return count;
}

// 保存所有饮品信息到文件，返回保存的饮品数量
// filename is expected to be the base filename (e.g., "drinks.dat")
int save_drinks(const char* filename, DrinkNode* head) {
    char full_path[1024];
    // Construct the full path using the macro defined in CMakeLists.txt
    snprintf(full_path, sizeof(full_path), "%s/%s", SOURCE_DATA_PATH, filename);

    FILE* fp = fopen(full_path, "wb");
    if (!fp) {
        // Optional: Print an error message if file couldn't be opened
        // perror(full_path);
        return 0;
    }
    int count = 0;
    DrinkNode* p = head;
    while (p) {
        if (fwrite(&p->data, sizeof(Drink), 1, fp) != 1) break;
        p = p->next;
        count++;
    }
    fclose(fp);
    return count;
}

// 添加新饮品到链表尾部，若编号已存在则不添加，返回1成功，0已存在
int add_drink(DrinkNode** head, const Drink* new_drink) {
    if (find_drink_by_id(*head, new_drink->id)) {
        // 已存在该编号饮品，不添加
        return 0;
    }
    DrinkNode* node = (DrinkNode*)malloc(sizeof(DrinkNode));
    if (!node) return 0;
    node->data = *new_drink;
    node->next = NULL;
    if (*head == NULL) {
        *head = node;
    } else {
        DrinkNode* p = *head;
        while (p->next) p = p->next;
        p->next = node;
    }
    return 1;
}

// 根据饮品编号删除饮品，成功返回1，失败返回0
int delete_drink(DrinkNode** head, int drink_id) {
    DrinkNode* p = *head, *prev = NULL;
    while (p) {
        if (p->data.id == drink_id) {
            if (prev) prev->next = p->next;
            else *head = p->next;
            free(p);
            return 1;
        }
        prev = p;
        p = p->next;
    }
    return 0;
}

// 查找饮品，返回指向该节点的指针，未找到返回NULL
DrinkNode* find_drink_by_id(DrinkNode* head, int drink_id) {
    while (head) {
        if (head->data.id == drink_id) return head;
        head = head->next;
    }
    return NULL;
}

// 修改饮品信息，成功返回1，失败返回0
int update_drink(DrinkNode* head, const Drink* updated_drink) {
    DrinkNode* node = find_drink_by_id(head, updated_drink->id);
    if (!node) return 0;
    node->data = *updated_drink;
    return 1;
}

// 按名称、分类、口味等条件查询饮品，返回链表（需手动释放）
DrinkNode* query_drinks(DrinkNode* head, const char* name, const char* category, const char* taste) {
    DrinkNode* result = NULL, *tail = NULL;
    while (head) {
        int match = 1;
        if (name && strlen(name) > 0 && strstr(head->data.name, name) == NULL) match = 0;
        if (category && strlen(category) > 0 && strstr(head->data.category, category) == NULL) match = 0;
        if (taste && strlen(taste) > 0 && strstr(head->data.taste, taste) == NULL) match = 0;
        if (match) {
            DrinkNode* node = (DrinkNode*)malloc(sizeof(DrinkNode));
            if (!node) break;
            node->data = head->data;
            node->next = NULL;
            if (!result) result = node;
            else tail->next = node;
            tail = node;
        }
        head = head->next;
    }
    return result;
}

// 打印所有饮品信息（调试用）
void print_all_drinks(DrinkNode* head) {
    printf("编号\t名称\t分类\t口味\t库存\t价格\n");
    while (head) {
        printf("%d\t%s\t%s\t%s\t%d\t%.2f\n",
            head->data.id,
            head->data.name,
            head->data.category,
            head->data.taste,
            head->data.stock,
            head->data.price
        );
        head = head->next;
    }
}

// 释放链表内存
void free_all_drinks(DrinkNode* head) {
    while (head) {
        DrinkNode* tmp = head;
        head = head->next;
        free(tmp);
    }
}